package com.example.book_system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.book_system.common.Result;
import com.example.book_system.entity.Book;
import com.example.book_system.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 这是管理员服务的实现层
 * @author Administrator
 */
@Service("adminService")
public class AdminServiceImpl implements IAdminService{

    private final BookMapper bookMapper;

    @Autowired
    AdminServiceImpl(BookMapper bookMapper){
        this.bookMapper = bookMapper;
    }

    @Override
    public Result<String> addBook(Book book) {
        if(book.getTotal() < 0){
            return new Result<>(Result.FAILED_CODE, "书籍总量不能为负数", "failed");
        }
        if(book.getBorrow() < 0){
            return new Result<>(Result.FAILED_CODE, "书籍借阅量不能为负数", "failed");
        }
        if(book.getTotal() < book.getBorrow()){
            return new Result<>(Result.FAILED_CODE, "书籍借阅量不能大于书籍总量", "failed");
        }

        // 1. 如果书籍不存在 直接插入
        // 2. 如果书籍存在 则叠加存量
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("isbn", book.getIsbn());
        Book oldBook = bookMapper.selectOne(wrapper);
        if(oldBook == null){
            bookMapper.insert(book);
            return new Result<>(Result.SUCCESS_CODE, "新增书籍成功", "success");
        }else{
            oldBook.setTotal(oldBook.getTotal() + book.getTotal());
            bookMapper.update(oldBook, wrapper);
            return new Result<>(Result.SUCCESS_CODE, "书籍补加成功", "success");
        }
    }
}
